package com.blrs.web.controller.message;

import com.blrs.common.annotation.Anonymous;
import com.blrs.common.core.domain.AjaxResult;
import com.blrs.common.core.redis.RedisCache;
import com.blrs.common.utils.SmsHttpApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

import static com.blrs.common.utils.SmsHttpApi.sendMtMessage;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private RedisCache redisCache;

    @Anonymous
    @GetMapping("/sendMessage/{phone}")
    public AjaxResult sendMessage(@PathVariable("phone") String phone) throws Exception {
        //1.判断手机号是否在60s内是否发送过短信
        String key = "message:" + phone;
        if (redisCache.hasKey(key)) {
            return AjaxResult.error("短信发送频繁，请60s后再试");
        } else {
            //1.生成6位随机验证码
            String code = String.format("%06d", (int) (Math.random() * 1000000));
            //2.发送短信
            String s = sendMtMessage(
                    "30181",
                    "t7CKeT",
                    phone,
                    "1069100010060",
                    "【湖南数生调试】;验证码:" + code + ";有效期:1分钟;请勿回复",
                    "PUSH"
            );
            //3.保存发送记录到redis
            redisCache.setCacheObject(key,code,60, TimeUnit.SECONDS);
            System.out.println(code);
            return AjaxResult.success("短信发送成功");
        }
    }



}
